package com.sunnada.weixin.util.weixinPay;

import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaProperty;

import com.sunnada.weixin.util.weixinPay.DateEasy;

import sun.misc.BASE64Encoder;

@SuppressWarnings("rawtypes")
public class Utils {
	private static long seqNumber=0;
	//程序控制的序列
	private  synchronized static  long getSeqNumber(){
		seqNumber=seqNumber+1;
		if(seqNumber==100000000){
			seqNumber=0;
		}
		return seqNumber;
	}
	/**
	 * @Description:补位方法
	 * @author yewg   2014-9-22    
	 * @param srcStr  字符串
	 * @param lenth   目标长度
	 * @param supplyChar  填充符号
	 * @return
	 */
	private static String fillStrWithChar(String srcStr, int lenth, char supplyChar) {
		if (srcStr == null)
			srcStr = supplyChar + "";
		if (srcStr.length() < lenth) {
			StringBuffer seqTmpBuffer = new StringBuffer();
			for (int i = 0; i < (lenth - srcStr.length()); i++) {
				seqTmpBuffer.append(supplyChar);
			}
			srcStr = seqTmpBuffer.append(srcStr).toString();
		} else if (srcStr.length() > lenth) {
			int len = srcStr.length();
			int differenceLen = len - lenth;
			srcStr = srcStr.substring(differenceLen, len);
		}
		return srcStr;
	}
	/**
	 * 生成指定长度的序列号
	 * @param len
	 * @param supplyChar
	 * @return
	 */
	public static String getSeqStr(int len,char supplyChar){
		long num=getSeqNumber();
		String str=fillStrWithChar(num+"",len,supplyChar);
		return str;
	}
	//12时间戳+8位固定长度序列号
	public static String getOrderNo(){
		DateEasy d = new DateEasy(new Date());
		String ret=d.format("yyMMddHHmmss")+getSeqStr(8,'0');
		return ret;
	}
	//12时间戳+8位固定长度序列号
	public static String getRequestId(){
		DateEasy d = new DateEasy(new Date());
		String ret=d.format("yyMMddHHmmss")+getSeqStr(6,'0');
		return ret;
	}
	/**
	 * @Description:格式化金额  0.00
	 * @author yewg   2014-9-22    
	 * @param str
	 * @return
	 */
	public static String formatDouble(String str){
		String s=new DecimalFormat("0.00").format(Double.parseDouble(str));
		 return s;
	}
	/**
	 * 按参数格式化当前时间
	 * 
	 * @param format
	 * @return
	 */
	public static String getDateFormat(String format) {
		Date now = new Date();
		SimpleDateFormat sf = new SimpleDateFormat(format);
		return sf.format(now);
	}

	

	public static List<String> filterDupl(List<String> slist) {
		List<String> tlist = new ArrayList<String>();
		Map<String, String> tm = new HashMap<String, String>();

		for (Iterator<String> it = slist.iterator(); it.hasNext();) {
			String s = it.next();
			tm.put(s, s);
		}
		Collection<String> c = tm.values();
		for (Iterator<String> it = c.iterator(); it.hasNext();) {
			tlist.add(it.next());
		}
		return tlist;
	}

	public static List<String[]> filterDuplArray(List<String[]> slist) {
		List<String[]> tlist = new ArrayList<String[]>();
		Map<String, String[]> tm = new HashMap<String, String[]>();

		for (Iterator<String[]> it = slist.iterator(); it.hasNext();) {
			String[] s = it.next();
			tm.put(s[0], s);
		}
		Collection<String[]> c = tm.values();
		for (Iterator<String[]> it = c.iterator(); it.hasNext();) {
			tlist.add(it.next());
		}
		return tlist;
	}

	public static String transToNormalString(Date dTime) {
		if (dTime == null) {
			dTime = new Date();
		}
		SimpleDateFormat formatter1 = new SimpleDateFormat("yyyyMMddHHmmss");
		return formatter1.format(dTime);
	}

	

	// 将iByte 转换为4位16进制数
	public static String wordToFourAscii(int iByte) {
		String strResult = Integer.toHexString(iByte);
		if (strResult.length() < 4) {
			for (int i = strResult.length(); i < 4; i++) {
				strResult = "0" + strResult;
			}
		}
		if (strResult.length() > 4) {
			strResult = strResult.substring(strResult.length() - 4);
		}
		return strResult;
	}

	public static boolean isNull(String s) {
		if (s == null || "null".equals(s) || "".equals(s)) {
			return true;
		}
		return false;
	}

	public static boolean isNotNull(String s) {
		return !isNull(s);
	}

	public static Double getMoney(String money) {
		if (money == null || "null".equals(money) || "".equals(money))
			return 0.0;
		return Double.valueOf(money);
	}

	/**
	 * @explain 拷贝 BeanUtilsBean 的copyProperties加入判断当值不为空时填充
	 * @author chs 2012-12-6
	 * @update chs 2012-12-6
	 * @param dest
	 * @param orig
	 *            void
	 */
	public static void copyBean(Object dest, Object orig) {
		try {
			BeanUtilsBean beanUtils = BeanUtilsBean.getInstance();
			if (dest == null) {
				throw new IllegalArgumentException(
						"No destination bean specified");
			}
			if (orig == null) {
				throw new IllegalArgumentException("No origin bean specified");
			}

			if (orig instanceof DynaBean) {
				DynaProperty origDescriptors[] = ((DynaBean) orig)
						.getDynaClass().getDynaProperties();
				for (int i = 0; i < origDescriptors.length; i++) {
					String name = origDescriptors[i].getName();
					if (beanUtils.getPropertyUtils().isWriteable(dest, name)) {
						Object value = ((DynaBean) orig).get(name);
						beanUtils.copyProperty(dest, name, value);
					}
				}
			} else if (orig instanceof Map) {
				Iterator names = ((Map) orig).keySet().iterator();
				while (names.hasNext()) {
					String name = (String) names.next();
					if (beanUtils.getPropertyUtils().isWriteable(dest, name)) {
						Object value = ((Map) orig).get(name);
						beanUtils.copyProperty(dest, name, value);
					}
				}
			} else {
				PropertyDescriptor origDescriptors[] = beanUtils
						.getPropertyUtils().getPropertyDescriptors(orig);
				for (int i = 0; i < origDescriptors.length; i++) {
					String name = origDescriptors[i].getName();
					if ("class".equals(name)) {
						continue;
					}
					if (beanUtils.getPropertyUtils().isReadable(orig, name)
							&& beanUtils.getPropertyUtils().isWriteable(dest,
									name)) {
						Object value = beanUtils.getPropertyUtils()
								.getSimpleProperty(orig, name);
						if (value != null)
							beanUtils.copyProperty(dest, name, value);

					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @explain 获得IP地址
	 * @author chs 2012-12-6
	 * @update chs 2012-12-6
	 * @param request
	 * @return
	 * @throws Exception
	 *             String
	 */
	public static String getIpAddr(HttpServletRequest request) throws Exception {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * @explain 获得mac地址
	 * @author chs 2012-12-6
	 * @update chs 2012-12-6
	 * @param ip
	 * @return
	 * @throws Exception
	 *             String
	 */
	public static String getMACAddress(String ip) throws Exception {
		String macAddress = "";
		final String LOOPBACK_ADDRESS = "127.0.0.1";
		if (LOOPBACK_ADDRESS.equals(ip)) {
			InetAddress inetAddress = InetAddress.getLocalHost();
			byte[] mac = NetworkInterface.getByInetAddress(inetAddress)
					.getHardwareAddress();
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < mac.length; i++) {
				if (i != 0) {
					sb.append("-");
				}
				String s = Integer.toHexString(mac[i] & 0xFF);
				sb.append(s.length() == 1 ? 0 + s : s);
			}
			macAddress = sb.toString().trim().toUpperCase();
			return macAddress;
		}
		// 获取非本地IP的MAC地址
		String str = "";
		try {
			Process pp = Runtime.getRuntime().exec("nbtstat -a " + ip);
			InputStreamReader ir = new InputStreamReader(pp.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);
			for (int i = 1; i < 100; i++) {
				str = input.readLine();
				if (str != null) {
					if (str.indexOf("MAC Address") > 1) {
						macAddress = str.substring(
								str.indexOf("MAC Address") + 14, str.length());
						break;
					}
				}
			}
		} catch (IOException ex) {
			return "Can't Get MAC Address!";
		}
		return macAddress;
	}

	/***
	 * num处理
	 * 
	 * @param num
	 * @return
	 */
	public static Integer getNum(String num) {
		if (Utils.isNotNull(num)) {
			return Integer.valueOf(num);
		}
		return 0;
	}

	/**
	 * 
	 * 功能描述：(ajax字json返回值)
	 * 
	 * @author linjm
	 * @date 2013-8-6 下午4:34:16
	 * 
	 * @param @param jsonArray
	 * @param @param response
	 * @return void
	 * @class ( 被哪些类调用)
	 * @mender (修改者)
	 * @updatetime(修改时间)
	 */
	public static void outJSONArray(net.sf.json.JSONArray jsonArray,
			HttpServletResponse response) {
		// 设置字符集
		response.setContentType("text/json; charset=UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print(jsonArray);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	public static void outJSONObject(net.sf.json.JSONObject json,
			HttpServletResponse response) {
		// 设置字符集
		response.setContentType("text/json; charset=UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print(json);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	/**
	 * 
	 * 功能描述：(ajax字符串返回值)
	 * 
	 * @author linjm
	 * @date 2013-8-6 下午4:32:36
	 * 
	 * @param @param response
	 * @param @param out
	 * @param @param str
	 * @param @return
	 * @return PrintWriter
	 * @class ( 被哪些类调用)
	 * @mender (修改者)
	 * @updatetime(修改时间)
	 */
	public static PrintWriter outMessage(HttpServletResponse response,
			PrintWriter out, String str) {
		// 预留 备份下发命令 存入下发日志表
		try {
			out = response.getWriter();
			out.print(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (out != null) {
			try {
				out.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return out;
	}

	public static String md5(String message) {
		try {
			MessageDigest md = MessageDigest.getInstance("md5");
			byte md5[] = md.digest(message.getBytes());
			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(md5);
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}

	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}
	public static String replaceNull(String str){
		String temp = "";
		if(str!=null&&!"null".equals(str)){
			temp = str;
		}
		return temp;
	}
	public static String generateCode(int intCode,String bit){
		 String res = String.format("%0"+bit+"d", intCode);
		 return res;
	}
	
	public String[] split(String regex,String str){
		boolean end=false;
		if(str.endsWith(regex)){
			str=str+" ";
			end=true;
		}
		String[] temp=str.split(regex);
		if(end){
			temp[temp.length-1]="";
		}
		return temp;
	}
	
	/**
     * @Description:元转分
     * @author yewg   2014-10-27    
     * @param num
     * @return
     */
    public static String yuan2fen(String num){
		double value=Double.parseDouble(num);
		double s=value*100;
		int ret = new BigDecimal(""+s).setScale(0, BigDecimal.ROUND_HALF_UP).intValue(); 
		return new Integer(ret).toString();
    }
    
    
	/**
     * @Description:list转String
     * @author yangzh   2016-06-22    
     * @param list,separator
     * @return
     */
    public static String listToString(List list, char separator) {
        StringBuilder sb = new StringBuilder();    
        for (int i = 0; i < list.size(); i++) {        
        	sb.append(list.get(i)).append(separator);    
        }    
        return sb.toString().substring(0,sb.toString().length()-1);
     }
    
}
